package com.addzero.kmp.generrator

import com.addzero.kmp.consts.GEN_PKG
import com.addzero.kmp.processor.entity.JdbcTableMetadata
import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.Dependencies


fun generateMetadataCode(
    pkg: String, codeGenerator: CodeGenerator, tables: List<JdbcTableMetadata>,
) {
    val content = """
            package $pkg

            import com.addzero.kmp.processor.entity.JdbcColumnMetadata
            import com.addzero.kmp.processor.entity.JdbcTableMetadata

            /**
             * JDBC元数据
             *
             * 自动生成的数据库表结构元数据
             */
            val jdbcMetadata: List<JdbcTableMetadata> = listOf(
                ${
        tables.joinToString(",\n") { table ->
            """
                    JdbcTableMetadata(
                        tableName = "${table.tableName}",
                        schema = "${table.schema}",
                        tableType = "${table.tableType}",
                        remarks = "${table.remarks}",
                        columns = listOf(
                            ${
                table.columns.joinToString(",\n") { column ->
                    """
                                JdbcColumnMetadata(
                                    tableName = "${column.tableName}",
                                    columnName = "${column.columnName}",
                                    jdbcType = ${column.jdbcType},
                                    columnType = "${column.columnType}",
                                    columnLength = ${column.columnLength},
                                    nullable = ${column.nullable},
                                    nullableFlag = "${column.nullableFlag}",
                                    remarks = "${column.remarks}",
                                    defaultValue = ${if (column.defaultValue != null) "\"${column.defaultValue}\"" else "null"},
                                    isPrimaryKey = ${column.isPrimaryKey}
                                )""".trimIndent()
                }
            }
                        )
                    )""".trimIndent()
        }
    }
            )
        """.trimIndent()

    // 生成文件
    codeGenerator.createNewFile(
        dependencies = Dependencies(aggregating = true), packageName = pkg, fileName = "JdbcMetadataInit"
    ).use { output ->
        output
        output.write(content.toByteArray())
    }
}

